package com.two.screen.water.balance.net.api

import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import io.reactivex.ObservableEmitter
import io.reactivex.disposables.Disposable

object PollingOrderApi {
    var countTimeJly1 = 0
    var mOeJly: ObservableEmitter<String>? = null
    var mD: Disposable? = null

    var mar_id: String? = SPUtils.getString(Params.mar_id)
    var mer_id: String? = SPUtils.getString(Params.merchant_id)

    fun pollingLocalOrderList(mActivity: BaseActivity) {
//        cancelPollingOrderList()
//        Observable.create(ObservableOnSubscribe<String> { e ->
//            countTimeJly1++
//            mOeJly = e
//            //mActivity.d("pollingOrderList create")
//            if (countTimeJly1 % 1 == 0) {
//                var list = App.mDaoMaster?.newSession()?.queryBuilder(OrderBean::class.java)
//                    ?.where(OrderBeanDao.Properties.UploadStatus.eq(0))//上传状态。//0:未上传，1:上传成功,2:上传失败
//                    ?.offset(0)?.limit(1)?.list()
//                mActivity.d("pollingOrderList=>list.size:${list?.size}")
//                e.onComplete()
//                if (list != null && list.isNotEmpty()) {
//                    var goodInfo = list.first()
//                    NormalApi.getData(sortedMapOf(Params.data_json to CommUtils.gson.toJson(orderBean2UploadBean(list.first())))," Urls.order")
//                        .compose(RxUtils.aLifecycle(mActivity))
//                        .compose(RxUtils.io())
//                        .subscribe(object : NormalObserver<BaseData>(mActivity) {
//                            override fun onError(t: Throwable) {
//                                App.mDaoSession?.orderBeanDao?.updateInTx(goodInfo?.apply { uploadStatus = 2 })
//                                e.onComplete()
//                            }
//
//                            override fun dataIsNull(t: BaseBean<out BaseData>) {
//                                App.mDaoSession?.orderBeanDao?.updateInTx(goodInfo?.apply { uploadStatus = 1 })
//                                EventBusUtil.sendEvent(Event(EventCode.REFRESH_DATA))
//                                mActivity.d("onNext:$t")
//                                e.onComplete()
//                            }
//
//                            override fun onSuccessNext(t: BaseBean<out BaseData>) {
//                                dataIsNull(t)
//                            }
//                        })
//                } else {
//                    e.onComplete()
//                }
//            } else {
//                e.onComplete()
//            }
//        })
//            .repeatWhen {
//                return@repeatWhen it.flatMap {
//                    return@flatMap io.reactivex.Observable.timer(5, java.util.concurrent.TimeUnit.SECONDS)
//                }
//            }
//            .compose(RxUtils.aLifecycle(mActivity))
//            .subscribe(object : MyObserver<String>() {
//                override fun onSubscribe(d: io.reactivex.disposables.Disposable) {
//                    super.onSubscribe(d)
//                    mD = d
//                }
//
//                override fun onError(e: kotlin.Throwable) {
//                    mActivity.d("pollingOrderList=>:onError:$e")
//                }
//
//                override fun onNext(t: kotlin.String) {
//                    mActivity.d("pollingOrderList=>:onNext:$t")
//                }
//            })
    }

//    private fun orderBean2UploadBean(goodInfo: OrderBean): UploadOrderBean {
//        return UploadOrderBean().apply {
//            scale_sn = goodInfo.scale_sn
//            mar_id = PollingOrderApi.mar_id
//            mer_id = PollingOrderApi.mer_id
//            order_sn = goodInfo.order_sn
//            //付款方式，1现金、2刷卡、3聚合支付，4会员支付(目前只支持现金)
////            pay_type = when (goodInfo.pay_type) {
////                //1现金支付，2支付宝，3、微信支付、4会员卡。
////                1 -> 1
////                2, 3 -> 3
////                4 -> 4
////                else -> 1
////            }
//            deal_type = "01"//交易类型 默认01
//            total_price = goodInfo.total_price
//            total_weight = goodInfo.total_weight
//            detail = goodInfo.goodsList?.map {
//                Goods().apply {
//                    this.goods_id = it.product_id
//                    this.name = it.product_name
//                    this.weight = it.weight
//                    this.price = it.sale_price
//                   // this.unit = it.unit_id//商品单位类型 ，1：重量。2，个数
//                }
//            }?.toMutableList()
//        }
//
//    }

    fun cancelPollingOrderList() {
        try {
            mD?.dispose()
            mD = null
            mOeJly = null
        } catch (e: Exception) {
            ToastUtil.showToast("自动上传失败:$e")
        }
    }

//    fun uploadDate(position: Int, orderBean: OrderBean, mAdapter: LocalOrderReportFragment.LocalOrderAdapter, mFragment: LocalOrderReportFragment, mActivit: BaseActivity) {
//        NormalApi.getData(sortedMapOf(Params.data to CommUtils.gson.toJson(orderBean2UploadBean(orderBean))), Urls.order)
//            .compose(RxUtils.io())
//            .compose(RxUtils.aLifecycle(mFragment))
//            .subscribe(object : DialogObserver<BaseData>(mActivit, "正在上传...") {
//                override fun onError(e: Throwable) {
//                    orderBean.apply { uploadStatus = 2 }
//                    mAdapter.data[position] = orderBean
//                    App.mDaoSession?.orderBeanDao?.updateInTx(orderBean)
//                    mAdapter.notifyItemChanged(position)
//                    super.onError(e)
//                }
//
//                override fun dataIsNull(t: BaseBean<out BaseData>) {
//                    onSuccessNext(t)
//                }
//
//                override fun onSuccessNext(t: BaseBean<out BaseData>) {
//                    orderBean.apply { uploadStatus = 1 }
//                    mAdapter.data[position] = orderBean
//                    App.mDaoSession?.orderBeanDao?.updateInTx(orderBean)
//                    mAdapter.notifyItemChanged(position)
//                }
//            })
//    }

//    fun onDelClick(mActivity: BaseActivity, carInfoBean: OrderBean, apiCallBack: ApiCallBack) {
//        Observable.create(ObservableOnSubscribe<OrderBean> { e ->
//            App.mDaoSession?.orderBeanDao?.delete(carInfoBean)
//            mActivity.mLoadingDialog.dismiss()
//            e.onNext(carInfoBean)
//        })
//            .compose(RxUtils.io())
//            .compose(RxUtils.aLifecycle(mActivity))
//            .doOnSubscribe {
//                mActivity.mLoadingDialog.mTitle = "正在删除..."
//                mActivity.mLoadingDialog.show()
//            }
//            .subscribe(object : MyObserver<OrderBean>() {
//                override fun onNext(t: OrderBean) {
//                    mActivity.mLoadingDialog.dismiss()
//                    apiCallBack.success()
//                }
//
//                override fun onError(e: Throwable) {
//                    ToastUtil.showToast(e.message.toString())
//                    mActivity.mLoadingDialog.dismiss()
//                }
//            })
//    }
//
//    fun onSwitchUploadStatus(mActivity: BaseActivity, apiCallBack: ApiCallBack) {
//        //在线程操作
//        Observable.create(ObservableOnSubscribe<Int> { e ->
//            try {
//                var tmpList = App.mDaoSession?.queryBuilder(OrderBean::class.java)
//                    ?.where(OrderBeanDao.Properties.UploadStatus.eq(2))   //上传状态。0:未上传，1:上传成功,2:上传失败
//                    ?.list()?.apply { forEach { it.uploadStatus = 0 } }
//                if (tmpList?.isNotEmpty() == true) App.mDaoSession?.orderBeanDao?.updateInTx(tmpList)
//                apiCallBack.success()
//                Thread.sleep(1000)
//                e.onNext(0)
//                e.onComplete()
//            } catch (ex: Exception) {
//                e.onError(ex)
//            }
//        })
//            .compose(RxUtils.io())
//            .compose(RxUtils.aLifecycle(mActivity))
//            .doOnSubscribe {
//                mActivity.mLoadingDialog.mTitle = "正在转换..."
//                mActivity.mLoadingDialog.show()
//            }
//            .subscribe(object : MyObserver<Int>() {
//                override fun onNext(t: Int) {
//                    ToastUtil.showToast("转换成功!")
//                    mActivity.mLoadingDialog.dismiss()
//                }
//
//                override fun onError(e: Throwable) {
//                    ToastUtil.showToast(e.message.toString())
//                    mActivity.mLoadingDialog.dismiss()
//                }
//            })
//    }

    //打印订单
//    fun onPrintOrder(acty: IndexActivityOld, orderBean: OrderBean?, foodList: List<ProductBean>? = null) {
//        Thread(Runnable {
//
//        }).start()
//    }
}

